package com.neteast.androidclient.newscenter.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLDecoder;

import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.neteast.androidclient.newscenter.Global;
import com.neteast.androidclient.newscenter.R;
import com.neteast.androidclient.newscenter.domain.Information;

public class JsonUtil {
	/**
	 * 解析json字符串，封装成Information对象返回
	 * @param data
	 * @return
	 */
	public static Information parse(Context context,String data) {
		
		if (!data.startsWith("{\"Info_id\"")) {
			return null;
		}
		try {
			JSONObject jsonObject=new JSONObject(data);
			Information information=new Information();
			
			long limitTime = jsonObject.optLong("Limit_time")*1000;
			Log.i("test", "limitTime="+limitTime);
			information.sendTime=jsonObject.optLong("Send_time")*1000;
			//判断是否过期
			if (System.currentTimeMillis()>limitTime) {
				return null;
			}
			information.infoId= jsonObject.optLong("Info_id");
			information.infoTypeId=jsonObject.optInt("Info_type_id");
			switch (information.infoTypeId) {
			case Global.INFO_TYPE_SYS:
				parseSysInfo(context,information,jsonObject);
				break;
			case Global.INFO_TYPE_APP:
				parseAppInfo(context,information,jsonObject);
				break;
			case Global.INFO_TYPE_INTERACTIVE:
				parseUserInfo(context,information,jsonObject);
				break;
			}
			information.textContent=URLDecoder.decode(jsonObject.getString("TextContent"), "utf-8");
			information.goURL=jsonObject.optString("Url");
			return information;
		} catch (Exception e) {
			Log.e("test", e.toString());
		}
		return null;
	}
	/**
	 * 解析互动消息
	 * @param context
	 * @param information
	 * @param jsonObject
	 * @throws JSONException
	 */
	private static void parseUserInfo(Context context, Information information,JSONObject jsonObject) throws JSONException {
		information.userId=jsonObject.optLong("From_User_id");
		information.userName=jsonObject.optString("From_User_name");
		information.interactiveType=jsonObject.optInt("Interactive_info_type");
		Resources resources = context.getResources();
		switch (information.interactiveType) {
		case Global.INFO_INTERACTIVE_MOVIE:
			information.infoThumbnail = resources.getDrawable(R.drawable.thumbnail_movie);
			information.ineractiveTypeContent = resources.getString(R.string.info_interactive_movie);
			break;
		case Global.INFO_INTERACTIVE_MUSIC:
			information.infoThumbnail = resources.getDrawable(R.drawable.thumbnail_music);
			information.ineractiveTypeContent = resources.getString(R.string.info_interactive_music);
			break;
		case Global.INFO_INTERACTIVE_PICTURE:
			information.infoThumbnail = resources.getDrawable(R.drawable.thumbnail_pic);
			information.ineractiveTypeContent = resources.getString(R.string.info_interactive_picture);
			break;
		case Global.INFO_INTERACTIVE_APP:
			information.infoThumbnail = resources.getDrawable(R.drawable.thumbnail_app);
			information.ineractiveTypeContent = resources.getString(R.string.info_interactive_app);
			break;
		}
	}
	/**
	 * 解析系统消息
	 * @param context
	 * @param information
	 * @param jsonObject
	 * @throws JSONException
	 */
	private static void parseSysInfo(Context context, Information information,JSONObject jsonObject) throws JSONException {
		String picUrl = jsonObject.optString("Picture");
		if (picUrl!=null&&!picUrl.equals("")) {
			information.weight=2;
			information.picUrl=picUrl;
		}
	}
	/**
	 * 解析应用消息
	 * @param context
	 * @param information
	 * @param jsonObject
	 * @throws JSONException
	 */
	private static void parseAppInfo(Context context, Information information,JSONObject jsonObject) throws JSONException {
		information.appId=jsonObject.optInt("Application_id");
		information.appName=jsonObject.optString("Application_name");
	}
	/**
	 * 将用户中心的字段转换为json
	 * @param context
	 * @param bundle
	 * @return
	 * @throws Exception
	 */
	public static JSONObject parseUserCenterInfo2Json(Context context,Bundle bundle) throws Exception{
		
		JSONObject obj=new JSONObject();
		
		obj.put("contactId", LoginUtil.getUserId(context));
		obj.put("username", bundle.getString("username"));
		
		String identityCard = bundle.getString("identityCard");
		obj.put("identityCard", identityCard==null?JSONObject.NULL:identityCard);
		
		String love = bundle.getString("love");
		obj.put("love", TextUtils.isEmpty(love)?JSONObject.NULL:love);
		
		String QQ = bundle.getString("QQ");
		obj.put("QQ", TextUtils.isEmpty(QQ)?JSONObject.NULL:QQ);
		
		String MSN = bundle.getString("MSN");
		obj.put("MSN", TextUtils.isEmpty(MSN)?JSONObject.NULL:MSN);
		
		String school = bundle.getString("school");
		obj.put("school", TextUtils.isEmpty(school)?JSONObject.NULL:school);
		
		String organization = bundle.getString("organization");
		obj.put("organization", TextUtils.isEmpty(organization)?JSONObject.NULL:organization);
		
		return obj;
	}
	/**
	 * 将json转换为用户中心的字段
	 * @param context
	 * @param content
	 * @return
	 * @throws Exception 
	 */
	public static Bundle parseJson2UserCenterInfo(Context context,InputStream ins) throws Exception {
		byte[] data = getDataFromInputStream(ins);
		if (data!=null&&data.length>0) {
			String json=new String(data, "UTF-8");
			Log.i("test", "json="+json);
			if (json.trim().startsWith("{\"code\"")) { 
				JSONObject obj = new JSONObject(json);
				switch (obj.optInt("code")) {
				case 1:
					break;
				default:
					throw new RuntimeException(obj.optString("description"));
				}
			}

			if (json.startsWith("{\"contactId\"")) {
				JSONObject obj=new JSONObject(json);
				Bundle bundle=new Bundle();
				bundle.putString("contactId", obj.optString("contactId"));
				bundle.putString("username", obj.optString("username"));
				bundle.putString("identityCard", obj.optString("identityCard"));
				bundle.putString("love", obj.optString("love"));
				bundle.putString("QQ", obj.optString("QQ"));
				bundle.putString("MSN", obj.optString("MSN"));
				bundle.putString("school", obj.optString("school"));
				bundle.putString("organization", obj.optString("organization"));
				return bundle;
			}
			
			throw new RuntimeException("获取信息失败");
		} else {
			throw new RuntimeException("获取信息失败");
		}
	}
	
	/**
	 * 从输入流获取数据
	 * @param inputStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] getDataFromInputStream(InputStream inputStream) throws Exception {
		ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
		int len=0;
		byte[] buffer=new byte[1024];
		while ((len=inputStream.read(buffer))>0) {
			outputStream.write(buffer, 0, len);
		}
		inputStream.close();
		return outputStream.toByteArray();
	}
}
